// API包装器 - 统一错误处理和重试机制
export class ApiWrapper {
  constructor(apiInstance, options = {}) {
    this.api = apiInstance;
    this.options = {
      enableRetry: options.enableRetry || false,
      maxRetries: options.maxRetries || 3,
      retryDelay: options.retryDelay || 1000,
      enableLogging: options.enableLogging || false,
      ...options
    };
  }

  async request(method, url, config = {}) {
    let lastError;
    const maxAttempts = this.options.enableRetry ? this.options.maxRetries + 1 : 1;

    for (let attempt = 1; attempt <= maxAttempts; attempt++) {
      try {
        if (this.options.enableLogging) {
          console.log(`[API] ${method.toUpperCase()} ${url} - Attempt ${attempt}`);
        }

        const response = await this.api[method](url, config);
        
        if (this.options.enableLogging) {
          console.log(`[API] ${method.toUpperCase()} ${url} - Success`);
        }

        return response;
      } catch (error) {
        lastError = error;
        
        if (this.options.enableLogging) {
          console.error(`[API] ${method.toUpperCase()} ${url} - Error:`, error.message);
        }

        // 如果是最后一次尝试或者不需要重试，直接抛出错误
        if (attempt === maxAttempts || !this.shouldRetry(error)) {
          break;
        }

        // 等待后重试
        await this.delay(this.options.retryDelay * attempt);
      }
    }

    throw lastError;
  }

  shouldRetry(error) {
    // 只对网络错误和5xx服务器错误进行重试
    return (
      !error.response || 
      error.response.status >= 500 ||
      error.code === 'NETWORK_ERROR'
    );
  }

  delay(ms) {
    return new Promise(resolve => setTimeout(resolve, ms));
  }

  get(url, config) {
    return this.request('get', url, config);
  }

  post(url, data, config) {
    return this.request('post', url, { ...config, data });
  }

  put(url, data, config) {
    return this.request('put', url, { ...config, data });
  }

  delete(url, config) {
    return this.request('delete', url, config);
  }
}

// 输入校验器
export class InputValidator {
  static validateDateRange(startDate, endDate) {
    const errors = [];
    
    if (!startDate || !endDate) {
      errors.push('请选择完整的日期范围');
      return errors;
    }

    if (startDate.isAfter(endDate)) {
      errors.push('开始日期不能晚于结束日期');
    }

    const daysDiff = endDate.diff(startDate, 'days');
    if (daysDiff > 365) {
      errors.push('日期范围不能超过365天');
    }

    if (startDate.isAfter(new Date())) {
      errors.push('开始日期不能是未来日期');
    }

    return errors;
  }

  static validateRequired(value, fieldName) {
    if (!value || (typeof value === 'string' && value.trim() === '')) {
      return [`${fieldName}不能为空`];
    }
    return [];
  }

  static validateEmail(email) {
    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    if (!emailRegex.test(email)) {
      return ['请输入有效的邮箱地址'];
    }
    return [];
  }

  static validateNumber(value, min, max, fieldName) {
    const errors = [];
    const num = Number(value);
    
    if (isNaN(num)) {
      errors.push(`${fieldName}必须是数字`);
      return errors;
    }

    if (min !== undefined && num < min) {
      errors.push(`${fieldName}不能小于${min}`);
    }

    if (max !== undefined && num > max) {
      errors.push(`${fieldName}不能大于${max}`);
    }

    return errors;
  }
}

// 错误处理工具
export class ErrorHandler {
  static handleApiError(error, context = '') {
    let message = '操作失败，请稍后重试';
    
    if (error.response) {
      const { status, data } = error.response;
      
      switch (status) {
        case 400:
          message = data?.message || '请求参数错误';
          break;
        case 401:
          message = '登录已过期，请重新登录';
          break;
        case 403:
          message = '没有权限执行此操作';
          break;
        case 404:
          message = '请求的资源不存在';
          break;
        case 500:
          message = '服务器内部错误';
          break;
        default:
          message = data?.message || `服务器错误 (${status})`;
      }
    } else if (error.code === 'NETWORK_ERROR') {
      message = '网络连接失败，请检查网络设置';
    }

    if (context) {
      message = `${context}: ${message}`;
    }

    return message;
  }

  static logError(error, context = '') {
    console.error(`[Error] ${context}:`, {
      message: error.message,
      stack: error.stack,
      response: error.response?.data,
      status: error.response?.status
    });
  }
}